# -*- coding:utf-8 -*-
from selenium import webdriver
import  os
from selenium.webdriver.chrome.options import Options
import requests
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def cookie2json(req_Cookie):
    Cookielist = [x.split("=") for x in req_Cookie.split(";")]
    Cookie = {i[0]: "=".join(i[1:]) for i in Cookielist if i[0] not in ["path", "expires"]}
    return Cookie


def json2cookie(cookie):
    Cookielist = ["=".join(i) for i in cookie]
    Cookie = ";".join(Cookielist)
    return Cookie


def jar2cookie(cookie):
    cookie = [i["name"] + "=" + i["value"] for i in cookie]
    cookies = ";".join(cookie)
    return cookies


class JS():

    def __init__(self) -> None:
        self.postjson_js = '''function POST(url,data)
        {   a="3";
            var oAjax = new XMLHttpRequest();

            oAjax.open('POST', url, false);//false表示同步请求

            oAjax.setRequestHeader("Content-type", "application/json;chartset=UTF-8");

            oAjax.onreadystatechange = function() {
                        if (oAjax.readyState == 4 && oAjax.status == 200) {
                            console.log(oAjax.responseText);
                            a = oAjax.responseText;
                            return oAjax.responseText

                        } else {
                            console.log(oAjax);
                            return 0
                        }
                };
            oAjax.send(data);
            }
        '''
        self.post_js = '''function POST(url,data)
        {   a="";
            var oAjax = new XMLHttpRequest();

            oAjax.open('POST', url, false);//false表示同步请求

            oAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

            oAjax.onreadystatechange = function() {
                        if (oAjax.readyState == 4 && oAjax.status == 200) {
                            console.log(oAjax.responseText);
                            a = oAjax.responseText;
                            return oAjax.responseText

                        } else {
                            console.log(oAjax);
                            return 0
                        }
            
                };
            oAjax.send(data);
            
            }
        
        
        '''
        self.post = '''POST("{}","{}")
            return a'''

        self.postjson = '''POST("{}",'{}')
            return a'''

        self.get = '''GET("{}")
            return a'''

        self.get_js = '''function GET(url)
            {   a="";
                var oAjax = new XMLHttpRequest();

                oAjax.open('GET', url, false);//false表示同步请求
                oAjax.setRequestHeader("accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");

                oAjax.onreadystatechange = function() {
                            if (oAjax.readyState == 4 && oAjax.status == 200) {
                                console.log(oAjax.responseText);
                                a=oAjax.responseText;
                                return oAjax.responseText

                            } else {
                                console.log(oAjax);
                                return 0
                            }
                
                    };
                oAjax.send(null);
                }
                
        '''

    def postjson_by_js(self, browser, url, data):
        js = self.postjson_js + self.postjson.format(url, data)
        return browser.execute_script(js)

    def post_by_js(self, browser, url, data):
        js = self.post_js + self.post.format(url, data)
        return browser.execute_script(js)

    def get_by_js(self, browser, url):
        return browser.execute_script(self.get_js + self.get.format(url))


def Driver():
    driver = "chromedriver.exe"  # chromedriver.exe位置
    existence = os.path.exists(driver)
    if existence:
        options = Options()
        # prefs = {
        #     'profile.default_content_setting_values': {
        #         'profile.managed_default_content_settings.images': 2,
        #         'permissions.default.stylesheet':2,
        #         'javascript': 1
        #     }
        # }
        # options.add_experimental_option('prefs', prefs)
        # options.add_experimental_option('excludeSwitches', ['enable-automation'])
        options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
        try:
            print(requests.get(url="http://127.0.0.1:9222", timeout=1).status_code)  # 测试连接
            # log("log.txt","1")
            browser = webdriver.Chrome(driver, options=options)
            # log("log.txt","")
            print("浏览器启动正常")
            return browser
        except Exception as e:
            print(e)
            print("浏览器未启动")

    return False


def Driver_headless(path=r"D:\Program Files\llq\CentBrowser\Application\chrome.exe"):
    options = webdriver.ChromeOptions()
    options.binary_location = path
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-gpu')
    options.add_argument('blink-settings=imagesEnabled=false')
    # 2代表禁止加载，1代表允许加载
    prefs = {
        'profile.default_content_setting_values': {
            'images': 2,
            'permissions.default.stylesheet': 2,
            'javascript': 1
        }
    }

    options.add_experimental_option('prefs', prefs)
    client = webdriver.Chrome(options=options, executable_path='chromedriver.exe')
    return client


def find(browser, xpath):
    element = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    return element


def find2(browser, xpath):
    element = WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.XPATH, xpath)))
    return element


if __name__ == '__main__':
    browser = Driver_headless()
